package com.android.nearshop.app.activity.main;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.forum.ForumActivity;
import com.android.nearshop.app.activity.guesslike.GuessLikeActivity;
import com.android.nearshop.app.activity.memdate.MemDateActivity;
import com.android.nearshop.app.activity.setting.SettingActivity;
import com.android.nearshop.app.activity.setting.SettingFunctionActivity;
import com.android.nearshop.app.activity.shop.CheapActivity;
import com.android.nearshop.app.widget.IndexTabView;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.business.update.UpdateManager;
import com.android.nearshop.business.update.UpdateManager.CHECK_RESULT;
import com.android.nearshop.business.update.UpdateManager.OnUpdateListener;
import com.android.nearshop.business.update.UpdateManager.UpdateInfo;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.CycledThread;
import com.android.nearshop.util.CycledThread.OnTimeoutListener;
import com.android.nearshop.util.ImageLoader;
import com.android.nearshop.util.ImageLoader.Imager;
import com.android.nearshop.util.LocationUtils;
import com.android.nearshop.util.NotifyListener;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-13
 * @see : 主界面
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class MainIndexActivity extends ActivityGroup 
implements OnClickListener
{
    private static final String TAG = "MainIndexActivity";
    public static final int TAB_INDEX_0 = -1;
    public static final int TAB_INDEX_1 = 0;
    public static final int TAB_INDEX_2 = 1;
    public static final int TAB_INDEX_3 = 2;
    public static final int TAB_INDEX_4 = 3;
    public static final int TAB_INDEX_5 = 4;
    private static Animation shakeAnim;
    private FrameLayout mTabContentLayout;
    private IndexTabView[] mBottomTabs = new IndexTabView[5];
    private View index_indac;
    private int mTabIconsNormal[];
    private int mTabIconsSelected[];
    private int mCurTab = -2;
    private int mReqTab = TAB_INDEX_0;
    private MyBMapManager mMapManager;
    private CycledThread limitThread;
    private Bitmap kaijiBmp;
    private Queue<Dialog> dialogs = new LinkedBlockingQueue<Dialog>();
    private Handler mHandler = new Handler();
    
    public MainIndexActivity()
    {       
        mMapManager = MyBMapManager.getInstace(this);
        mTabIconsNormal = new int[5];
        mTabIconsNormal[0] = R.drawable.index_disshop_normal;
        mTabIconsNormal[1] = R.drawable.index_guslike_normal;
        mTabIconsNormal[2] = R.drawable.index_memdate_normal;
        mTabIconsNormal[3] = R.drawable.index_group_normal;
        mTabIconsNormal[4] = R.drawable.index_setting_normal;
        mTabIconsSelected = new int[5];
        mTabIconsSelected[0] = R.drawable.index_disshop_selected;
        mTabIconsSelected[1] = R.drawable.index_guslike_selected;
        mTabIconsSelected[2] = R.drawable.index_memdate_selected;
        mTabIconsSelected[3] = R.drawable.index_group_selected;
        mTabIconsSelected[4] = R.drawable.index_setting_selected;
//        DataCacheManager.getInstance().getAreaList(null);
//        DataCacheManager.getInstance().getCateList(null);        
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_Translucent_NoTitleBar);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        handIntent();
        mMapManager.startKeepLocation();
        if(MyApplication.getContext().isFirst)
        {
            checkLimit();
            showKaijiView();
            checkUpdate(null);
        }else
        {
            showMainView();
        }
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        if(mCurTab != -2 && mCurTab != mReqTab)
        {
            onTabClick(mReqTab);
        }
        showGpsDialog();
        addShortCut();
    }
    
    @Override
    protected void onPause()
    {
        hideDialog();       
        super.onPause();
    }
    
    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        mReqTab = intent.getIntExtra(Constant.TAG_INDEX_TAB, mCurTab);
    }
    
    @Override
    protected void onDestroy()
    {
        // TODO ...
        super.onDestroy();       
    }
       
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main_menu, menu);//指定使用的XML
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.report:
		{
			SettingFunctionActivity.startActivity(this, SettingFunctionActivity.REPORT);
			break;
		}
    	case R.id.about_us:
		{
			SettingFunctionActivity.startActivity(this, SettingFunctionActivity.ABOUT_US);
			break;
		}
		case R.id.exit:
		{
			 showDialog(true,getString(R.string.shortcut_notify), getString(R.string.exit_review), null, 
		               getString(R.string.cancel),null, 
		               getString(R.string.sure), 
		                new DialogInterface.OnClickListener()
		                {
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                    	finish();
		            			MyApplication.getContext().exit();
		                    }
		                });
			break;
		}
		default:
			break;
		}
    	
    	return true;
    }
    
    private boolean isback = false;
    
    @Override
    public void onBackPressed()
    {
        if ((getCurrentActivity() instanceof ShakeShopActivity 
                || getCurrentActivity() instanceof SettingActivity)
                && ShakeShopActivity.isPopBack)
        {
            ShakeShopActivity.isPopBack = false;
            return;
        }
        
        Toast.makeText(this, R.string.back_exit, Toast.LENGTH_LONG).show();
        
        if(isback){
        	MainIndexActivity.super.onBackPressed();
        }
        
        isback = true;
        mHandler.postDelayed(new Runnable() {
			public void run() {
				isback = false;
			}
		}, 5000);
               
      
        return;
    }
        
    private void handIntent()
    {
        Intent it = getIntent();
        mReqTab = it.getIntExtra(Constant.TAG_INDEX_TAB, TAB_INDEX_0);
    }
    
    private void showKaijiView()
    {
        getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_kai_ji_dong_hua);
        final String img = MyApplication.getContext().getStartImg();
		// from SD cache
        if(img == null || !ImageLoader.getInstance().fileCached(img))
        {
            // 还没更新启动广告
            ImageView imgView = (ImageView)findViewById(R.id.kaiji_lay);
            imgView.setScaleType(ScaleType.FIT_XY);
            imgView.setBackgroundResource(R.drawable.kai_ji_dong_hua);
            // 获取动态更新的启动页面
            DataCacheManager.getInstance().getStartAdv(null,false);
            // 下载开机动画           
            new AsyncTask<Void, Void, Bitmap>()
            {
                @Override
                protected Bitmap doInBackground(Void... params)
                {                    
                    return ImageLoader.getInstance().getBitmap(new Imager(img, null,0, 0));
                }
                protected void onPostExecute(Bitmap result) 
                {
                   
                };
            }.execute();
        }else
        {
            // 已更新           
            new AsyncTask<Void, Void, Bitmap>()
            {
                @Override
                protected Bitmap doInBackground(Void... params)
                {                    
                    return ImageLoader.getInstance().getBitmap(new Imager(img, null,0, 0));
                }
                protected void onPostExecute(Bitmap result) 
                {
                    ImageView imgView = (ImageView)findViewById(R.id.kaiji_lay);
                    if(result != null)
                    {
                        kaijiBmp = result;
                        if(imgView != null)
                        {
                            imgView.setScaleType(ScaleType.CENTER);
                            imgView.setImageBitmap(result);
                        }
                    }else
                    {
                    	if(imgView != null)
                    	{
                    	    imgView.setScaleType(ScaleType.FIT_XY);
                            imgView.setBackgroundResource(R.drawable.kai_ji_dong_hua);
                    	}
                    }
                };
            }.execute();
        }
    }
    
    private void showGuideView()
    {       
        final RelativeLayout floatView = (RelativeLayout)findViewById(R.id.float_layout);
        floatView.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                floatView.setVisibility(View.GONE);
            }
        });
        floatView.setVisibility(View.VISIBLE);
    }
    
    private void showMainView()
    {
        // 不是第一次进入，已显示主界面，返回
        if( !MyApplication.getContext().isFirst && mTabContentLayout != null)
        {          
            return;
        }
        if(kaijiBmp != null && !kaijiBmp.isRecycled())
        {
            kaijiBmp.recycle();
            kaijiBmp = null;
            Log.d(TAG, "realease kaiji bitmap");
        }
        // 进入主界面
        MyApplication.getContext().isFirst = false;
        getLocalActivityManager().removeAllActivities();
        disableFullScreen();
        setContentView(R.layout.activity_main_index);
        initMainViews();
        onTabClick(mReqTab);
        if(MyApplication.getContext().isNeedGuide())
        {
            showGuideView();
        }
    }
    
    private void disableFullScreen()
    {
      WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
      localLayoutParams.flags = ( (~LayoutParams.FLAG_FULLSCREEN) & localLayoutParams.flags);
      getWindow().setAttributes(localLayoutParams);
      getWindow().clearFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, (~LayoutParams.FLAG_FULLSCREEN));
    }
    
    private void initMainViews()
    {
        mTabContentLayout = (FrameLayout)findViewById(R.id.container);
        
        this.mBottomTabs[0] = ((IndexTabView)findViewById(R.id.tab1));
        this.mBottomTabs[0].setOnClickListener(this);
        this.mBottomTabs[1] = ((IndexTabView)findViewById(R.id.tab2));
        this.mBottomTabs[1].setOnClickListener(this);
        this.mBottomTabs[2] = ((IndexTabView)findViewById(R.id.tab3));
        this.mBottomTabs[2].setOnClickListener(this);
        this.mBottomTabs[3] = ((IndexTabView)findViewById(R.id.tab4));
        this.mBottomTabs[3].setOnClickListener(this);
        this.mBottomTabs[4] = ((IndexTabView)findViewById(R.id.tab5));
        this.mBottomTabs[4].setOnClickListener(this);
        for (int i = 0; i < this.mBottomTabs.length; i++)
        {
            this.mBottomTabs[i].setImageResource(mTabIconsNormal[i]);
        }
        this.index_indac = findViewById(R.id.index_indac);
    }

    private void onTabClick(int tabId)
    {
        Log.d(TAG, "onTabClick : mCurTab = "+mCurTab +" ,tabId = "+ tabId);
        if(mCurTab != -2 && mCurTab == tabId)
        {
            // 当前重复返回
            return;
        }else             
        {
            // 请求为当前
            if(tabId == -2 )
            {
                tabId = TAB_INDEX_0;
            }
            mCurTab = tabId;
            mReqTab = mCurTab;
        }
        onTabChanged(mCurTab);
        switch(mCurTab)
        {
            case TAB_INDEX_0:
            {
                showTab0();
                break;
            }
            case TAB_INDEX_1:
            {
                showTab1();
                break;
            }
            case TAB_INDEX_2:
            {
                showTab2();
                break;
            }
            case TAB_INDEX_3:
            {
                showTab3();
                break;
            }
            case TAB_INDEX_4:
            {
                showTab4();
                break;
            }
            case TAB_INDEX_5:
            {
                showTab5();
                break;
            }
        }
    }
    
    private void onTabChanged(int tabId)
    {
        for (int i = 0; i < this.mBottomTabs.length; i++)
        {
            this.mBottomTabs[i].reset(mTabIconsNormal[i]);
        }
        if(tabId >= 0)
        {
            this.index_indac.setVisibility(View.GONE);
            this.mBottomTabs[tabId].setClick();
            this.mBottomTabs[tabId].setImageResource(mTabIconsSelected[tabId]);
        }else
        {
            this.index_indac.setVisibility(View.VISIBLE);
        }
    }
    
    // 摇一摇主界面
    private void showTab0()
    {
        showTabContent("tab0",ShakeShopActivity.getStartActivity(this));
    }
    // 优惠商家
    private void showTab1()
    {
        showTabContent("tab1",new Intent(this,CheapActivity.class));
    }
    // 猜你喜欢
    private void showTab2()
    {
        showTabContent("tab2",new Intent(this,GuessLikeActivity.class));
    }
    // 会员日
    private void showTab3()
    {
    	showTabContent("tab3",new Intent(this,MemDateActivity.class));
    }
    // 社区
    private void showTab4()
    {
    	showTabContent("tab4",new Intent(this,ForumActivity.class));
    }
    // 设置 
    private void showTab5()
    {
        showTabContent("tab5",SettingActivity.getStartActivity(this));
    }
    
    private void showTabContent(String id, Intent subWindows)
    {
        if(subWindows == null) return;
        Window localWindow = getLocalActivityManager().startActivity(id, subWindows);
        mTabContentLayout.removeAllViews();
        mTabContentLayout.addView(localWindow.getDecorView());
    }
    
    // 显示 摇一摇 主界面
    public void gotoShake()
    {
        onTabClick(TAB_INDEX_0);
    }
    
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.tab1:
            {
                onTabClick(TAB_INDEX_1);
                break;
            }
            case R.id.tab2:
            {
                onTabClick(TAB_INDEX_2);
                break;
            }
            case R.id.tab3:
            {
                onTabClick(TAB_INDEX_3);
                break;
            }
            case R.id.tab4:
            {
                onTabClick(TAB_INDEX_4);
                break;
            }
            case R.id.tab5:
            {
                onTabClick(TAB_INDEX_5);
                break;
            }
        }
    }
   
    private void checkLimit()
    {
        if( limitThread == null)
        {
            limitThread = new CycledThread(200, 5000, new OnTimeoutListener()
            {
                @Override
                public void onTimeout()
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            showMainView();
                        }
                    });
                }
            });
            limitThread.start();
        }
    }
    
    public void checkUpdate(final NotifyListener<Boolean> listener)
    {
        UpdateManager.getInstacnce(this).startCheck(new OnUpdateListener()
        {
            @Override
            public void onUpdate(CHECK_RESULT result, final UpdateInfo updateInfo)
            {               
                    if(updateInfo != null && 
                      (result == CHECK_RESULT.NEED || result == CHECK_RESULT.HAVE))
                    {
                        MyApplication.getContext().isLastVer = false;
                        if(listener != null)
                        {
                            listener.onSucceed(false);
                        }
                        
                        int layId = R.layout.dialog_update_tip;        
                        View dialogView = getLayoutInflater().inflate(layId, null);
                        TextView version_name = (TextView)dialogView.findViewById(R.id.version_name);
                        TextView time = (TextView)dialogView.findViewById(R.id.time);
                        TextView size = (TextView)dialogView.findViewById(R.id.size); 
                        TextView info = (TextView)dialogView.findViewById(R.id.info);                       
                        version_name.setText(updateInfo.versionName);
                        time.setText(updateInfo.time);
                        size.setText(updateInfo.size);
                        info.setText(updateInfo.desc);
                        
                        showDialog(true,"发现新版本", null, dialogView, 
                                result == CHECK_RESULT.NEED?null:"以后再说", null,
                                result == CHECK_RESULT.NEED?"确定":"立即更新",
                                new DialogInterface.OnClickListener() 
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) 
                                    {
                                        String saveDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                                        saveDir += "/update/";
                                        UpdateManager.getInstacnce(MainIndexActivity.this)
                                            .startUpdateNotify(updateInfo.path, saveDir);
                                        dialog.dismiss();
                                    }
                                });
                    }else
                    if(result == CHECK_RESULT.NONE)
                    {
                        MyApplication.getContext().isLastVer = true;
                        if(listener != null)
                        {
                            listener.onSucceed(true);
                        }
                    }else
                    {
                        if(listener != null)
                        {
                            listener.onError(-1);
                        }
                    }
                }
        });
    }
    
    /** 显示自定义弹出窗体*/
    public Dialog showDialog(boolean isCenter, String title, String msg,View contentView,
            String cancelbtnName, DialogInterface.OnClickListener cancelbtnListener,
            String okbtnName,DialogInterface.OnClickListener okbtnListener)
    {
        // 在创建新的窗体
        Builder builder = new AlertDialog.Builder(this);
        if(title != null)
        {
            builder.setTitle(title);
        }
        if(msg != null)
        {
            builder.setMessage(msg);
        }
        if(cancelbtnName != null)
        {
            builder.setNegativeButton(cancelbtnName,cancelbtnListener);
        }
        if(okbtnName != null)
        {
            builder.setPositiveButton(okbtnName, okbtnListener);
        }
        if(contentView != null)
        {
            builder.setView(contentView);
        }
                
        Dialog dialog = builder.create();
        if(!isCenter)
        {
            Window mwindow=dialog.getWindow(); 
            mwindow.setGravity(Gravity.LEFT | Gravity.TOP);
            WindowManager.LayoutParams lp=mwindow.getAttributes(); 
            lp.x=20;
            lp.y=50;
            mwindow.setAttributes(lp);
        }
        addQueueDialog(dialog);
        return dialog;
    }
    
    /** 添加到窗口显示队列中 */
    private void addQueueDialog(Dialog dialog)
    {
        // 取消事件监听器
        dialog.setOnDismissListener(new OnDismissListener()
        {            
            @Override
            public void onDismiss(DialogInterface dialog)
            {
                dialogs.poll();
                showQueueDialog();
            }
        });
        dialogs.offer(dialog);
        showQueueDialog();
    }
    
    /** 显示队列中窗口 */
    private void showQueueDialog()
    {
        if(!dialogs.isEmpty())
        {
            if(!dialogs.peek().isShowing())
            {
                dialogs.peek().show();
            }
        }
    }
    
    /** 关闭自定义弹出窗体 */   
    private void hideDialog()
    {
        if(dialogs != null && dialogs.size() > 0)
        {
            if(!dialogs.isEmpty())
            {
                Dialog dialog = dialogs.peek();
                if(dialog.isShowing())
                {
                    dialog.dismiss();
                }
            }
        }
    }
    
    /** 添加快捷图标 */
    /**
     * 
     */
    private void addShortCut()
    {
        if(MyApplication.getContext().isShortCut() || MyApplication.getContext().isShortCutTip)
        {
            // 已存在
            return;
        }                
        // 显示窗口
        MyApplication.getContext().isShortCutTip = true;
        MyApplication.getContext().setShortCut(true);
        showDialog(true, getString(R.string.shortcut_notify), getString(R.string.shortcut_notify_text),
                  null, getString(R.string.cancel), null,
                  getString(R.string.sure), new DialogInterface.OnClickListener()
                 {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        Intent intent = new Intent(
                                "com.android.launcher.action.INSTALL_SHORTCUT");
                        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                                getString(R.string.app_name));
                        // 是否可以有多个快捷方式的副本，参数如果是true就可以生成多个快捷方式，如果是false就不会重复添加
                        intent.putExtra("duplicate", false);

                        Intent intent2 = new Intent(Intent.ACTION_MAIN);
                        intent2.addCategory(Intent.CATEGORY_LAUNCHER);
                        // 删除的应用程序的ComponentName，即应用程序包名+activity的名字
                        intent2.setComponent(new ComponentName(
                                getPackageName(), getPackageName() + ".app.activity.main.MainIndexActivity"));

                        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
                        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                                Intent.ShortcutIconResource.fromContext(
                                        MainIndexActivity.this,
                                        R.drawable.ic_launcher));
                        sendBroadcast(intent);
                        MyApplication.getContext().setShortCut(true);
                    }
                });
    }
    
    /** 如果没有GPS，则提示GPS是否要打开 */
    private void showGpsDialog()
    {
        if(!MyApplication.getContext().isGpsTip)
        {
            if(!LocationUtils.isGPSOpen(this, false, false))
            {
                MyApplication.getContext().isGpsTip = true;
                addQueueDialog(LocationUtils.openGPSDialog(this));
            }
        }
    }
    
    public static void startActivity(Context context, int tabIndex)
    {
        if(tabIndex < TAB_INDEX_0 || tabIndex > TAB_INDEX_5)
        {
            // 非法
            tabIndex = TAB_INDEX_0;
        }
        Intent it = new Intent(context, MainIndexActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        it.putExtra(Constant.TAG_INDEX_TAB, tabIndex);
        context.startActivity(it);
    }

    // 回到摇一摇主界面,如果view 不为null的话，摇晃一下才返回
    public static void gotoShake(final Activity activity, final View view)
    {
        if(view != null)
        {
            if(shakeAnim == null)
            {
                shakeAnim = AnimationUtils.loadAnimation(activity, R.anim.anim_shake);
            }
            view.startAnimation(shakeAnim);
            view.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    view.clearAnimation();
                    gotoShake(activity);
                }
            }, 500);
        }else
        {
            gotoShake(activity);
        }
    }
    
    private static void gotoShake(Activity activity)
    {
        if ( activity.getParent() != null && activity.getParent() instanceof MainIndexActivity)
        {
            ((MainIndexActivity)activity.getParent()).gotoShake();
        }else
        {
            MainIndexActivity.startActivity(activity, MainIndexActivity.TAB_INDEX_0);
            activity.finish();
        }
    }
}
